package cn.tedu.ivos.application.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos.application.pojo.dto.ApplicationSaveDTO;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos.application.service.ApplicationService;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author liyuehui
 * @time 2024/7/15 14:46
 */
@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private AuditService auditService;
    @Override
    public void save(ApplicationSaveDTO applicationSaveParam) {
        log.debug("保存申请单业务:applicationSaveParam={}",applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam,application);
        //新增申请单,初始状态为"已发起"
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());

        //遇到的问题:新增申请单对应的审批单数据时,审批数据没有申请单的id
        //原因:id是一个比较特殊的属性,无法通过任何select条件获取
        //解决方案:给insert方法对应的SQL上加 useGeneratedKeys="true" keyProperty="id"
        //效果:JDBC会为当前的application对象自动生成自增主键并且把生成的主键赋值给当前application对象的id字段
        applicationMapper.insert(application);

        //还需要调用审批业务层,为当前申请单同步新增对应的审批数据
        auditService.insert(application);
    }

    /**
     * 查询申请单
     * @param applicationQuery
     * @return List<ApplicationVO>
     */
    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务:applicationQuery={}",applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        return list;
    }
}
